import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
import { OrderCityEntity } from '../entity/city';
import { OrderShopEntity } from '../entity/shop';
import { OrderOrderEntity } from '../entity/order';
import { OrderGoodsEntity } from '../entity/goods';

/**
 * 订单模块-店铺信息Service
 */
@Provide()
export class OrderDataboardService extends BaseService {
    @InjectEntityModel(OrderCityEntity)
    orderCityEntity: Repository<OrderCityEntity>;

    @InjectEntityModel(OrderShopEntity)
    orderShopEntity: Repository<OrderShopEntity>;

    @InjectEntityModel(OrderOrderEntity)
    orderOrderEntity: Repository<OrderOrderEntity>;

    @InjectEntityModel(OrderGoodsEntity)
    orderGoodsEntity: Repository<OrderGoodsEntity>;

    @Inject()
    ctx;

    // 门店数据看板
    async tongkangShopBoard(params) {
        const { cityId, shopId, isAgent, goodsMoney } = params;
        console.log('tongkangShopBoard', isAgent, this.ctx.admin?.userId)
        let shopIds = [];
        let goodsIds = [];
        if (cityId) {
            shopIds = await this.orderShopEntity.find({
                where: {
                    cityId
                }
            });
            shopIds = shopIds.map(shop => shop.id);
        }
        if (shopId) {
            shopIds = [shopId];
        }
        if (goodsMoney) {
            if (goodsMoney == 3980) {
                    goodsIds = await this.orderGoodsEntity.find({
                        where: {
                            goodsPrice: In([3980, 4280]),
                        }
                    });
            } else {
                goodsIds = await this.orderGoodsEntity.find({
                    where: {
                        goodsPrice: goodsMoney,
                    }
                });
            }
            goodsIds = goodsIds.map(goods => goods.id);
        }
        if (isAgent) {
            shopIds = await this.orderShopEntity.find({
                where: {
                    agentId: this.ctx.admin?.userId,
                }
            });
            shopIds = shopIds.map(shop => shop.id);
        }

        console.log('sss', params, shopIds, goodsIds)
        // let orderResult = [];
        const orderResult = await this.orderOrderEntity.createQueryBuilder('');
        orderResult.andWhere('payStatus = 1');
        
        
        if ((cityId || shopId) && shopIds.length === 0) {
            return {};
        }

        if (goodsIds.length > 0) {
            orderResult.andWhere('GoodIds IN (:goodsIds)', { goodsIds: goodsIds });
        }

        if (shopIds.length > 0) {
            orderResult.andWhere('shopId IN (:shopIds)', { shopIds: shopIds });
        }

        // 只查询正常订单，客情订单不统计
        orderResult.andWhere('orderType is null or orderType = :orderType', {
            orderType: 'addOrder',
        });
        
        const orderResultList = await orderResult.getMany();
        console.log('orderResultList', goodsIds[0], goodsIds, goodsIds.length, orderResultList.length)

        // console.log('orderResult', orderResult)
       // 遍历orderResult，统计每个城市、门店的订单数量和金额
        const cityArr = await this.orderCityEntity.find({});
        const shopArr = await this.orderShopEntity.find({});
        // const goodsArr = await this.orderGoodsEntity.find({});
        const result = {};

          if (shopId && orderResultList.length === 0) {
          const shop = shopArr.find(shopItem => shopItem.id == shopId)
            console.log('shop', shopId, shop)
            if (!result[shop.cityId]) {
                result[shop.cityId] = {
                    cityId: shop.cityId,
                    cityName: cityArr.find(city => city.id === shop.cityId).cityName,
                    shopArr: [],
                };
            }
            if (!result[shop.cityId]['shopArr'].find(shopItem => shopItem.shopId === shopId)) {
                result[shop.cityId]['shopArr'].push({
                    cityId: shop.cityId,
                    cityName: result[shop.cityId]['cityName'],
                    shopId: shop.id,
                    shopName: shop.name,
                    orderCount: 0,
                    amount: 0
                });
            }
        }

          orderResultList.forEach(item => {
          const { shopId, payAmount } = item;
            const shop = shopArr.find(shop => shop.id === shopId);
            const city = cityArr.find(city => city.id === shop.cityId);
            if (!result[shop.cityId]) {
                result[shop.cityId] = {
                    cityId: shop.cityId,
                    cityName: city.cityName,
                    shopArr: [],
                };
            }
            if (!result[shop.cityId]['shopArr'].find(shopItem => shopItem.shopId === shopId)) {
                result[shop.cityId]['shopArr'].push({
                    cityId: shop.cityId,
                    cityName: result[shop.cityId]['cityName'],
                    shopId: shop.id,
                    shopName: shop.name,
                    orderCount: 0,
                    amount: 0
                });
            }
            result[shop.cityId]['shopArr'].find(shopItem => shopItem.shopId === shopId).orderCount++;
            result[shop.cityId]['shopArr'].find(shopItem => shopItem.shopId === shopId).amount += Number(payAmount);
        });

        // 每个城市需要计算合计
        Object.keys(result).forEach(cityId => {
            result[cityId]['shopCount'] = result[cityId]['shopArr'].length;
            result[cityId]['orderCount'] = result[cityId]['shopArr'].reduce((pre, cur) => pre + cur.orderCount, 0);
            result[cityId]['amount'] = result[cityId]['shopArr'].reduce((pre, cur) => pre + cur.amount, 0);
        });

        

        return result;
        // console.log('result', result)
    }
}
